package com.yilin.tms.data.components;

import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.yilin.commons.util.JsonUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

@Component
public class PdfTool {

    private String pdfToolExePath;

    /**
     * htmlToPdf新
     * */
    public boolean htmlToPdf(List<String> htmlList, String outPath) {
        try{
            String json = JsonUtil.objectToJson(htmlList);
            File tempHtmlFile = File.createTempFile("tempHtml", ".html");
            FileWriter htmlWriter = new FileWriter(tempHtmlFile);
            for (String html : htmlList) {
                htmlWriter.write(html);
                htmlWriter.write("<div style=\"page-break-before: always;\"></div>");
            }
            htmlWriter.close();
            // 指定 wkhtmltopdf 命令和输入输出文件
            String cmd = String.format("%s %s %s",pdfToolExePath,tempHtmlFile.getPath(),outPath);
            Process process = Runtime.getRuntime().exec(cmd);
            int exitCode = process.waitFor();
            System.out.println("Exited with error code " + exitCode);
            return exitCode==0;
        }catch(Exception e){
            return false;
        }
    }

    /**
     * pdf生成水印
     */
    public String addWaterMarkRep(String pdfParentPath, String pdfName, String waterMarkContent) {
        return addWaterMark(pdfParentPath + "/" + pdfName + ".pdf", pdfParentPath + "/" + pdfName + "(水印)" + ".pdf", waterMarkContent, 12);
    }

    public  String addWaterMark(String inputFile, String outputFile, String waterMarkName, int numberOfPage) {
        try {
            // 水印的高和宽（参数可调节）
            int textH = 60;
            int textW = 170;
            // 间隔距离（参数可调节）
            int interval = 30;
            // 切记这里的参数是文件的路径 ，路径必须是双斜杠的如F:\\test.pdf，不能是F:/test.pdf 或者F:\test.pdf
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, Files.newOutputStream(Paths.get(outputFile)));
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.2f);//改透明度
            gs.setStrokeOpacity(0.4f);
            int total = reader.getNumberOfPages() + 1;
            JLabel label = new JLabel();
            label.setText(waterMarkName);
            PdfContentByte under;
            // 可添加多个水印
            Rectangle pageRect = null;
            label.setText(waterMarkName);
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                // 在内容上方加水印
                under = stamper.getOverContent(i);
                under.saveState();
                under.setGState(gs);
                under.beginText();
                under.setFontAndSize(base, 16);
                // 水印文字成30度角倾斜
                for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 3) {
                    for (int width = interval + textW; width < pageRect.getWidth() + textW;
                         width = width + textW * 2) {
                        under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, 30);
                    }
                }
                // 添加水印文字
                under.endText();
            }
            stamper.close();
            reader.close();
            return outputFile;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
